<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">-->
    <title>递归发起</title>
    <script src="genUrls.js"></script>
</head>
<body>
<p>使用promise 变种async 函数加 await 也可以做到</p>

<script>

    function oneByOne(urls) {

        function addImg(src, url) {
            var div = document.createElement("div");
            var img = document.createElement("img");
            var p = document.createElement("p");
            img.src = src;
            // img.setAttribute("crossOrigin", 'Anonymous');//跨域。canvas绘制时有用。
            p.innerText = url;

            div.appendChild(img);
            div.appendChild(p);

            document.body.appendChild(div);

        }

        // 递归发起，一个一个来
        function request(curr) {
            if (curr > urls.length - 1) {
                return;
            }
            var url = urls[curr];

            //模拟网络请求
            // new Promise(function (resolve, reject) {
            //
            //     // setTimeout(() => {
            //     // resolve({data: "哈哈……"});
            //     // }, 5);
            //
            // }).then(function (res) {
            //     console.log(res, curr, url);
            //     request(curr + 1);
            // });

            //真实网络请求
            var xhr = new XMLHttpRequest();
            xhr.open("get", url, true);//发起异步请求。同步请求被废弃了
            // 至关重要
            xhr.responseType = "blob";
            xhr.onload = function () {
                if (this.status == 200) {//跨域返回的也可以是200，服务器已经正确响应，但浏览器拒绝给出。
                    //得到一个blob对象
                    var blob = this.response;
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(blob);
                    oFileReader.onloadend = function (e) {
                        let base64 = e.target.result;
                        addImg(base64, url);
                        request(curr + 1);
                    }
                    oFileReader.onerror = function (e) {
                        addImg(undefined, url);
                        request(curr + 1);

                    }
                }
                else {
                    addImg(undefined, url);
                    request(curr + 1);
                }
            }

            try {
                xhr.send();
            }
            catch (e) {//断网或其他错误
                addImg(undefined, url);
                request(curr + 1);
                console.log("网络故障");
            }

        }

        request(0);
    }

    var urls = genUrls();

    oneByOne(urls);


</script>
</body>
</html>